import com.sun.org.apache.bcel.internal.generic.Select;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient {

    public static void main(String[] args) {
        try {
            Selector selector = Selector.open();

            {
                SocketChannel socketChannel = SocketChannel.open();
                InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8888);
                socketChannel.connect(inetSocketAddress);
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_WRITE);
                System.out.println("开始连接");
            }

            byte n=0;

            while(true){
                int num = selector.select();
//                System.out.println("num="+num);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if(selectionKey.isValid() && selectionKey.isConnectable()){
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector,SelectionKey.OP_WRITE);//这是错误的
                        System.out.println("已经连接");
//                        iterator.remove();
                    }else if((selectionKey.readyOps()&SelectionKey.OP_WRITE)==SelectionKey.OP_WRITE){
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
                        n++;
                        byteBuffer.clear();
                        byteBuffer.put(n);
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                        Thread.sleep(1000);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
